package com.example.qywechat.util;

import com.alibaba.fastjson.JSONObject;
import com.example.qywechat.model.Department;
import com.example.qywechat.model.User;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 王森
 */
@Component
public class QyWeChatUtil {
    //获取access_token的请求路径
    private static final String GETACCESSTOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET";
    //获取访问用户userid
    private static final String GETUSERID = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE";
    //企业微信id
    private static final String CORPID = "ww60f69edf84f8d24f";
    //企业微信密钥
    private static final String CORPSECRET = "biOI9gNQv_cFohAUdB1DYbm6Y7ghWjmXUyGm0TNhrk4";
    //应用id
    //@Value("${qywx.appid}")
    private static final String AGENTID = "1000002";
    //创建成员
    private static final String CREATEUSER = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN";
    //更新成员
    private static final String UPDATEUSER = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN";
    //删除成员
    private static final String DELECTEUSER = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=USERID";
    //创建部门
    private static final String CREATEDEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=ACCESS_TOKEN";
    //更新部门
    private static final String UPDATEDEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=ACCESS_TOKEN";
    //删除部门
    private static final String DELECTDEPARTMENT = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=ACCESS_TOKEN&id=ID";
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取企业微信access_token
     * @return
     */
    public JSONObject getAccessToken(){
        String wXaccess_token = (String) redisTemplate.opsForValue().get("WXaccess_token");

        //String wXaccess_token = null;
        if (StringUtils.isEmpty(wXaccess_token)){

            String url= GETACCESSTOKEN.replace("ID",CORPID).replace("SECRET",CORPSECRET);

            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url+"&debug=1", String.class);
            String body = responseEntity.getBody();
            JSONObject resBody = JSONObject.parseObject(body);
            String errcode = resBody.getString("errcode");
            if ("0".equals(errcode)){
                redisTemplate.opsForValue().set("WXaccess_token",resBody.toString(),2, TimeUnit.HOURS);
                return resBody;
            }else {
                return resBody;
            }
        }
        JSONObject redisAccessToken = JSONObject.parseObject(wXaccess_token);
        return redisAccessToken;
    }
    public Map getAppidAndAgentid(){
        Map<String, String> map = new HashMap<>();
        map.put("appid",CORPID);
        map.put("agentid",AGENTID);
        return map;
    }

    public String getUseridByCode(String code){
        if (StringUtils.isEmpty(code)){
            return "code为null";
        }
        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");

        String url = GETUSERID.replace("ACCESS_TOKEN",access_token).replace("CODE",code);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url+"&debug=1", String.class);
        String body = responseEntity.getBody();

        return body;
    }

    /**
     * 创建用户
     * @param user
     * @return
     */
    public ResponseEntity<String> createUser(User user){

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");
        String url= CREATEUSER.replace("ACCESS_TOKEN",access_token);

        HttpEntity<User> entity = new HttpEntity<User>(user, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url+"&debug=1", entity, String.class);
        System.out.println(responseEntity);
        return responseEntity;
    }
    /**
     * 更新用户
     * @param user
     * @return
     */
    public ResponseEntity<String> updateUser(User user){

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");
        String url= UPDATEUSER.replace("ACCESS_TOKEN",access_token);

        HttpEntity<User> entity = new HttpEntity<User>(user, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url+"&debug=1", entity, String.class);
        System.out.println(responseEntity);
        return responseEntity;
    }
    /**
     * 删除用户
     * @param userId
     * @return
     */
    public ResponseEntity<String> delectUser(String userId){

        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");
        String url= DELECTEUSER.replace("ACCESS_TOKEN",access_token).replace("USERID",userId);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url+"&debug=1", String.class);

        return responseEntity;
    }

    /**
     * 创建部门
     * @param department
     * @return
     */
    public ResponseEntity<String> createDepartment(Department department){

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");
        String url= CREATEDEPARTMENT.replace("ACCESS_TOKEN", access_token);

        HttpEntity<Department> entity = new HttpEntity<Department>(department, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url+"&debug=1", entity, String.class);
        System.out.println(responseEntity);
        return responseEntity;
    }
    /**
     * 更新部门
     * @param department
     * @return
     */
    public ResponseEntity<String> updateDepartment(Department department){

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");
        String url= UPDATEDEPARTMENT.replace("ACCESS_TOKEN", access_token);

        HttpEntity<Department> entity = new HttpEntity<Department>(department, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url+"&debug=1", entity, String.class);
        System.out.println(responseEntity);
        return responseEntity;
    }
    /**
     * 删除部门
     * @param departmentId
     * @return
     */
    public ResponseEntity<String> delectDepartment(String departmentId){

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject accessToken = getAccessToken();
        String access_token = (String) accessToken.get("access_token");
        String url= DELECTDEPARTMENT.replace("ACCESS_TOKEN", access_token).replace("ID",departmentId);


        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url+"&debug=1",String.class);
        System.out.println(responseEntity);
        return responseEntity;
    }

}